package com.itheima.home_work.test3;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) throws IOException {
        // 统计一篇文章中出现的指定字符的个数

        int count = 0; // 次数

        // 1. 创建流
        final FileReader fr = new FileReader("index.html");
        final FileWriter fw = new FileWriter("index.html", true);

        // 2. 读取流
        int len = -1;
        char[] carr = new char[1024];
        while ((len = fr.read(carr)) != -1) {
            final String str = new String(carr, 0, len);
            // 统计字符出现次数
            count += countStr(str, "黑马");
        }

        fw.write(System.lineSeparator());
        fw.write("黑马共出现了 " + count + " 次.");

        // 3. 关闭流
        fr.close();
        fw.close();

        System.out.println("黑马共出现了 " + count + " 次.");

    }

    public static int countStr(String countString, String childString) {
        Pattern p = Pattern.compile(childString, Pattern.CASE_INSENSITIVE);

        Matcher m = p.matcher(countString);

        int count = 0;

        while (m.find()) {
            count++;
        }

        return count;
    }
}
